package com.letoo.dragon.common.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.letoo.dragon.common.exception.BusinessException;

/**
 * SQL语句验证的工具类
 * 
 * @author: dengjie
 */
public final class SqlValidationUtils {

	/**
	 * 验证带变量符号@的sql是否存在delete|update|insert|drop禁止出现的语法，并且如果没有则自动生成可以执行的sql，
	 * 提供给SQL执行验证调用
	 * 
	 * @param sql sql语句
	 * @return 替换@后的sql，如果存在敏感词汇直接报BusinessException
	 */
	public static String validateAndMatchAtSymbol(String sql) {
		sql = " " + sql + " ";
		Pattern pp = Pattern.compile("[\\(|\\s](delete|update|insert|drop) ");
		Matcher mm = pp.matcher(sql);
		while (!mm.hitEnd() && mm.find()) {
			throw new BusinessException("sql语句存在敏感词汇：" + mm.group(1));
		}
		List<String> strs = new ArrayList<String>();
		String sqlnew = sql;
		Pattern p = Pattern.compile("@([\\w]*) ");
		Matcher m = p.matcher(sql);
		while (!m.hitEnd() && m.find()) {
			strs.add(m.group(1));
		}
		for (String str : strs) {
			sqlnew = sqlnew.replace("@" + str, "1");
		}
		return sqlnew;
	}

}